package com.dc.system.serviceImpl;

import com.dc.base.exception.BusinessException;
import com.dc.common.constants.ConstantsCommon;
import com.dc.common.em.EnumOperationModule;
import com.dc.common.model.BaseModel;
import com.dc.system.dto.SysMenuDTO;
import com.dc.system.mapper.RoleMapper;
import com.dc.system.model.SysMenu;
import com.dc.system.model.SysRole;
import com.dc.system.model.SysRolePermission;
import com.dc.system.model.SysUser;
import com.dc.system.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseModel insertRole(BaseModel baseModel, SysRole role, String permissionStr, String subPermissionStr, HttpServletRequest request) throws Exception {
        //验证数据
        if (role.getName() == null || "".equals(role.getName().trim())) {
            throw new BusinessException(-101, "角色名称不能为空");
        }
        if ("".equals(permissionStr.trim())) {
            throw new BusinessException(-102, "总系统权限设置获取失败");
        }
        if ("".equals(subPermissionStr.trim())) {
            throw new BusinessException(-103, "子系统权限设置获取失败");
        }
        //插入角色信息并获取到角色id
        SysUser user = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        role.setCreateUserId(user.getUserId());
        role.setCreateUserName(user.getName());
        role.setCreateTime(new Date());
        int lines = roleMapper.insertRole(role);
        if (lines <= 0 || role.getRoleId() <= 0) {
            throw new BusinessException(-104, "添加角色&权限失败");
        }
        int roleId = role.getRoleId();
        //处理数据
        List<SysRolePermission> permissionList = new ArrayList();
        //处理总系统权限数据
        String[] permissions = permissionStr.split(",");
        for (String permission : permissions) {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setFkRoleId(roleId);
            sysRolePermission.setCode(permission);
            sysRolePermission.setIsMain(1);
            sysRolePermission.setCreateUserId(user.getUserId());
            sysRolePermission.setCreateUserName(user.getName());
            sysRolePermission.setCreateTime(new Date());
            permissionList.add(sysRolePermission);
        }
        //处理子系统权限数据
        String[] subPermissions = subPermissionStr.split(",");
        for (String subPermission : subPermissions) {
            String[] codeAndValue = subPermission.split(":");
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setFkRoleId(roleId);
            sysRolePermission.setCode(codeAndValue[0]);
            sysRolePermission.setPermissionValue(codeAndValue[1]);
            sysRolePermission.setIsMain(0);
            sysRolePermission.setCreateUserId(user.getUserId());
            sysRolePermission.setCreateUserName(user.getName());
            sysRolePermission.setCreateTime(new Date());
            permissionList.add(sysRolePermission);
        }
        //插入权限表
        int lines2 = roleMapper.insertRolePermission(permissionList);
        if (lines2 <= 0) {
            throw new BusinessException(-105, "添加角色&权限失败");
        }
        baseModel.setMessage("添加角色&权限成功，重新登录后生效");
        return baseModel;
    }

    @Override
    public BaseModel getPermissionMenus(BaseModel baseModel) throws Exception {
        //查询总系统的一级二级菜单
        List<SysMenuDTO> firstSysMenus = roleMapper.getFirstMenu();
        //查询分系统下二级菜单
        List<SysMenuDTO> secondSysMenus = roleMapper.getSecondMenu();
        //处理分系统下的二级菜单，增加功能点的列表
        for (SysMenuDTO secondSysMenu : secondSysMenus) {
            String temp =EnumOperationModule.getOperationByCode(Integer.valueOf(secondSysMenu.getCode())) ;
            if (temp != null){
                secondSysMenu.setFunctions(temp.split(","));
            }

        }
        Map map = new HashMap();
        map.put("firstSysMenus", firstSysMenus);
        map.put("secondSysMenus", secondSysMenus);
        baseModel.setData(map);
        return baseModel;
    }

    @Override
    public BaseModel getUserMenus(BaseModel baseModel, HttpServletRequest request) throws Exception {
        //获取当前登录用户
        SysUser user = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        //获取当前用户的菜单权限
        List<SysRolePermission> userRolePermissionList = roleMapper.getUserRolePermission(user.getUserId());
        //获取到总系统的所有菜单
        List<SysMenuDTO> firstSysMenus = roleMapper.getFirstMenu();
        //进行2者比对，删除没有权限的菜单
        //先比对一级菜单名
        for (int i = 0; i < firstSysMenus.size(); i++) {
            boolean flag = false;
            for (SysRolePermission userRolePermission : userRolePermissionList) {
                if (firstSysMenus.get(i).getCode().equals(userRolePermission.getCode())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                firstSysMenus.remove(i);
                i--;
            }
        }
        //再比对二级菜单名称
        for (int i = 0; i < firstSysMenus.size(); i++) {
            for (int j = 0; j < firstSysMenus.get(i).getFirstMenuList().size(); j++) {
                boolean flag = false;
                for (SysRolePermission userRolePermission : userRolePermissionList) {
                    List<SysMenu> sysMenu = firstSysMenus.get(i).getFirstMenuList();
                    String code = sysMenu.get(j).getCode();
                    if (code.equals(userRolePermission.getCode())) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    firstSysMenus.get(i).getFirstMenuList().remove(j);
                    j--;
                }
            }
        }
        baseModel.setData(firstSysMenus);
        return baseModel;
    }

    @Override
    public BaseModel getUserSubMenusByCodeNum(BaseModel baseModel, HttpServletRequest request, String codeNum) throws Exception {
        //验证数据
        if(codeNum==null||"".equals(codeNum.trim())){
            throw new BusinessException(-101,"子系统的标示获取失败");
        }
        //获取当前登录用户
        SysUser user = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        //获取当前用户子系统菜单权限
        List<SysRolePermission> userRolePermissionList = roleMapper.getUserSubRolePermission(user.getUserId());
        //获取到对应code值的子系统的所有菜单
        List<SysMenuDTO> secondSysMenus = roleMapper.getSecondMenuByCode(codeNum);
        //进行2者比对，删除没有权限的菜单
        //比对二级菜单名称
        for (int i = 0; i < secondSysMenus.size(); i++) {
            for (int j = 0; j < secondSysMenus.get(i).getSecondSubMenuList().size(); j++) {
                boolean flag = false;
                for (SysRolePermission userRolePermission : userRolePermissionList) {
                    List<SysMenu> sysMenu = secondSysMenus.get(i).getSecondSubMenuList();
                    String code = sysMenu.get(j).getCode();
                    if (code.equals(userRolePermission.getCode())) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    secondSysMenus.get(i).getSecondSubMenuList().remove(j);
                    j--;
                }
            }
        }
        //去掉没有二级菜单的子系统菜单
        for(int i = 0; i < secondSysMenus.size(); i++){
            if(secondSysMenus.get(i).getSecondSubMenuList().size()<=0){
                secondSysMenus.remove(i);
                i--;
            }
        }
        baseModel.setData(secondSysMenus);
        return baseModel;
    }

    @Override
    public BaseModel getRoleIdAndNames(BaseModel baseModel) throws Exception{
        List<SysRole> roleList = roleMapper.getRoleIdAndNames();
        baseModel.setData(roleList);
        return baseModel;
    }

    @Override
    public BaseModel getRoles(BaseModel baseModel, SysRole role, HttpServletRequest request) throws Exception {
        //验证数据，处理数据
        Map map = new HashMap();
        if (baseModel.getKey() != null && !"".equals(baseModel.getKey().trim())) {
            map.put("key", baseModel.getKey().trim());
        } else {
            map.put("key", null);
        }
        //查询
        PageHelper.startPage(baseModel.getPage() <= 0 ? 1 : baseModel.getPage(), baseModel.getRows() <= 0 ? 10 : baseModel.getRows());
        List<SysRole> roleList = roleMapper.getRoles(map);
        PageInfo<SysRole> resultRoleList = new PageInfo(roleList);
        baseModel.setData(resultRoleList);
        return baseModel;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseModel updateRole(BaseModel baseModel, SysRole role, String permissionStr, String subPermissionStr, HttpServletRequest request) throws Exception {
        //验证数据
        if (role.getRoleId()<=0) {
            throw new BusinessException(-101, "角色唯一标识获取失败");
        }
        if (role.getName() == null || "".equals(role.getName().trim())) {
            throw new BusinessException(-102, "角色名称不能为空");
        }
        if ("".equals(permissionStr.trim())) {
            throw new BusinessException(-103, "总系统权限设置获取失败");
        }
        if ("".equals(subPermissionStr.trim())) {
            throw new BusinessException(-104, "子系统权限设置获取失败");
        }
        //根据id获取到角色
        SysRole roleById = roleMapper.getRoleById(role.getRoleId());
        if(roleById==null){
            throw new BusinessException(-105, "未查询到对应的角色信息");
        }else if(roleById.getVersion()!=role.getVersion()){
            throw new BusinessException(-106, "角色修改版本不一致");
        }
        roleById.setName(role.getName());
        roleById.setNote(role.getNote());
        //角色信息并获取到角色id
        SysUser user = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        roleById.setUpdateUserId(user.getUserId());
        roleById.setUpdateUserName(user.getName());
        roleById.setUpdateTime(new Date());
        int lines = roleMapper.updateRole(roleById);
        if (lines <= 0 ) {
            throw new BusinessException(-107, "修改角色&权限失败");
        }
        //删除原来的权限
        int roleId = role.getRoleId();
        roleMapper.delPermissionByRoleId(roleId);
        //处理数据
        List<SysRolePermission> permissionList = new ArrayList();
        //处理总系统权限数据
        String[] permissions = permissionStr.split(",");
        for (String permission : permissions) {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setFkRoleId(roleId);
            sysRolePermission.setCode(permission);
            sysRolePermission.setIsMain(1);
            sysRolePermission.setCreateUserId(user.getUserId());
            sysRolePermission.setCreateUserName(user.getName());
            sysRolePermission.setCreateTime(new Date());
            permissionList.add(sysRolePermission);
        }
        //处理子系统权限数据
        String[] subPermissions = subPermissionStr.split(",");
        for (String subPermission : subPermissions) {
            String[] codeAndValue = subPermission.split(":");
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setFkRoleId(roleId);
            sysRolePermission.setCode(codeAndValue[0]);
            sysRolePermission.setPermissionValue(codeAndValue[1]);
            sysRolePermission.setIsMain(0);
            sysRolePermission.setCreateUserId(user.getUserId());
            sysRolePermission.setCreateUserName(user.getName());
            sysRolePermission.setCreateTime(new Date());
            permissionList.add(sysRolePermission);
        }
        //插入权限表
        int lines2 = roleMapper.insertRolePermission(permissionList);
        if (lines2 <= 0) {
            throw new BusinessException(-108, "添加角色&权限失败");
        }
        baseModel.setMessage("修改角色&权限成功，重新登录后生效");
        return baseModel;
    }

    @Override
    public BaseModel getPermissionByRoleId(BaseModel baseModel, SysRole role) throws Exception{
        //验证数据
        if (role.getRoleId()<=0) {
            throw new BusinessException(-101, "角色唯一标识获取失败");
        }
        List<SysRolePermission> permissionList = roleMapper.getPermissionByRoleId(role);
        SysRole roleById = roleMapper.getRoleById(role.getRoleId());
        List list1 = new ArrayList();//存储总菜单权限code
        List list2 = new ArrayList();//存储子菜单权限code以及权限
        //处理总菜单权限
        for (SysRolePermission sysRolePermission: permissionList) {
            if(sysRolePermission.getIsMain()==1){
                list1.add(sysRolePermission.getCode());
            }else{
                String value = sysRolePermission.getPermissionValue();
                for(int i =0;i<value.length();i++){
                    if(value.charAt(i)=='1'){
                        list2.add(sysRolePermission.getCode()+"_"+i);
                    }
                }
            }
        }
        Map map = new HashMap();
        map.put("roleById",roleById);
        map.put("systemPermission",list1);
        map.put("subSystemPermission",list2);
        baseModel.setData(map);
        return baseModel;
    }

    @Override
    public BaseModel delRole(BaseModel baseModel, SysRole role, HttpServletRequest request) throws Exception{
        //验证数据
        if (role.getRoleId()<=0) {
            throw new BusinessException(-101, "角色唯一标识获取失败");
        }
        //根据id获取到角色
        SysRole roleById = roleMapper.getRoleById(role.getRoleId());
        if(roleById==null){
            throw new BusinessException(-102, "未查询到对应的角色信息");
        }
        roleById.setIsDeleted(0);
        //修改人信息
        SysUser user = (SysUser) request.getSession().getAttribute(ConstantsCommon.LOGIN_INFO);
        roleById.setUpdateUserId(user.getUserId());
        roleById.setUpdateUserName(user.getName());
        roleById.setUpdateTime(new Date());
        //删除
        int lines = roleMapper.updateRole(roleById);
        if (lines <= 0 ) {
            throw new BusinessException(-103, "删除角色&权限失败");
        }else {
            baseModel.setMessage("删除成功");
        }
        return baseModel;
    }
}
